import express, { Application } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import mongoose from 'mongoose';
import path from 'path';
import { logger } from './utils/logger';
import { errorHandler } from './middleware/errorHandler';
import config from './config/env';
import dbMonitor from './config/database';
import { cleanupTempFiles } from './config/storage';

// 路由导入
import authRoutes from './routes/auth';
import lessonPlanRoutes from './routes/lessonPlan';
import userRoutes from './routes/user';
import fileRoutes from './routes/file';
import categoryRoutes from './routes/category';
import notificationRoutes from './routes/notifications';

const app: Application = express();
const PORT = config.PORT;

// 基础中间件
app.use(helmet());
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// 限流中间件已移除，以确保公司内部项目的正常访问

// 静态文件服务
const uploadsPath = path.join(process.cwd(), 'uploads');
app.use('/uploads', express.static(uploadsPath));
logger.info(`静态文件服务路径: ${uploadsPath}`);

// 路由配置
app.use('/api/auth', authRoutes);
app.use('/api/lessonplans', lessonPlanRoutes);
app.use('/api/users', userRoutes);
app.use('/api/files', fileRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/notifications', notificationRoutes);

// 健康检查
app.get('/health', async (req, res) => {
  const dbStatus = dbMonitor.getConnectionStatus();
  const isHealthy = await dbMonitor.healthCheck();
  
  res.json({ 
    status: isHealthy ? 'ok' : 'error',
    timestamp: new Date().toISOString(),
    version: process.env.npm_package_version || '1.0.0',
    environment: config.NODE_ENV,
    database: {
      ...dbStatus,
      healthy: isHealthy
    }
  });
});

// 错误处理测试路由（仅开发环境）
if (config.NODE_ENV === 'development') {
  app.get('/test-error', (req, res, next) => {
    const error = new Error('这是一个测试错误') as any;
    error.statusCode = 400;
    next(error);
  });
}

// 404处理
app.use('*', (req, res, next) => {
  const error = new Error(`找不到路径: ${req.originalUrl}`) as any;
  error.statusCode = 404;
  next(error);
});

// 错误处理中间件
app.use(errorHandler);

// 连接数据库
const connectDB = async () => {
  await dbMonitor.connect();
};

// 启动服务器
const startServer = async () => {
  try {
    // 验证日志系统
    logger.info('日志系统初始化完成');
    logger.info(`环境配置: ${config.NODE_ENV}`);
    logger.info(`日志级别: ${config.LOG_LEVEL}`);
    
    await connectDB();
    app.listen(PORT, () => {
      logger.info(`服务器启动成功 - 端口: ${PORT}`);
      logger.info(`MongoDB连接: ${config.MONGODB_URI}`);
      logger.info(`服务器准备就绪 🚀`);
      
      // 启动定期清理临时文件任务（每天凌晨2点执行）
      setInterval(() => {
        const now = new Date();
        if (now.getHours() === 2 && now.getMinutes() === 0) {
          logger.info('开始清理临时文件...');
          cleanupTempFiles()
            .then(() => logger.info('临时文件清理完成'))
            .catch(error => logger.error('临时文件清理失败', { error }));
        }
      }, 60 * 1000); // 每分钟检查一次
    });
  } catch (error) {
    logger.error('服务器启动失败:', error);
    process.exit(1);
  }
};

startServer();

export default app;